package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.QianDaoBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.view.KCalendar;
import cn.com.xinjinfu.pdoulcProduct.view.MyDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import static cn.com.xinjinfu.pdoulcProduct.entity.QianDaoBean.*;

/**
 * 签到日历页面
 * Created by android-adt on 2016/4/6.
 */
public class QianDaoAct extends BaseActivity {

    private String date = null;// 设置默认选中的日期  格式为 “2014-04-05” 标准DATE格式
    private TextView calendar_month,tv_top_title;
    private ImageView qdangleleft,qdangleright;
    private KCalendar calendar;
    private List<String> timeList = new ArrayList<String>(); //设置标记列表
    private List<String> moneyList = new ArrayList<String>();
    private RequestQueue requen;
    private QianDaoBean qiandao;
    private String month,year;
    private double income;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_qiandao);
        TitleManager.showTitle(this, "签到记录", "");
        requen = Volley.newRequestQueue(this);
        qdangleleft = (ImageView) findViewById(R.id.qdangleleft);
        qdangleright = (ImageView) findViewById(R.id.qdangleright);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        calendar_month = (TextView) findViewById(R.id.tv_calendar_month);
        calendar = (KCalendar) findViewById(R.id.popupwindow_calendar);
        Bundle bundle = getIntent().getExtras();
        int code = bundle.getInt("code");
        income = bundle.getDouble("income");
        L.d("income============="+income+"code==="+code);
        if (code == -1){
            showPopwindow();
            findViewById(R.id.tv_error_hint).setVisibility(View.GONE);
        }else if (code == -5){
            findViewById(R.id.tv_error_hint).setVisibility(View.VISIBLE);
        }else {
            findViewById(R.id.tv_error_hint).setVisibility(View.GONE);
        }
        //获取当前月份
        year = calendar.getCalendarYear()+"";
        month = calendar.getCalendarMonth()+"";
        if (calendar.getCalendarMonth() < 10){
            month = "0" + calendar.getCalendarMonth();
        }
        calendar_month.setText(year + "年"
                + month + "月");
        loginRequest(year + "-" + month);

        //如果进入到日历界面指定月份，可以用到这个方法
//        if (null != date) {
//            int years = Integer.parseInt(date.substring(0,
//                    date.indexOf("-")));
//            int month = Integer.parseInt(date.substring(
//                    date.indexOf("-") + 1, date.lastIndexOf("-")));
//            calendar_month.setText(years + "年" + month + "月");
//            calendar.showCalendar(years, month);
//            calendar.setCalendarDayBgColor(date, R.drawable.calendar_day_bg2);
//        }
        qdangleleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.setLastMonth();
            }
        });
        qdangleright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.setNextMonth();
            }
        });
        //监听当前月份
        calendar.setOnCalendarDateChangedListener(new KCalendar.OnCalendarDateChangedListener() {
            public void onCalendarDateChanged(int year, int month) {
                String myMonth = null;
                if(month<10){
                    myMonth = "0"+ month;
                }else {
                    myMonth = ""+ month;
                }
                calendar_month.setText(year + "年" + myMonth + "月");
                loginRequest(year + "-" + myMonth);
            }
        });
    }

    private void upData(){
        ArrayList<SignList> signLists = qiandao.getSignList();
        for (SignList signList:signLists){
            timeList.add(signList.getSignDate());
            moneyList.add(TextViewUtil.getSumLength(signList.getSignAmount()));
        }
        if (timeList!=null && moneyList!=null){
            calendar.addMarks(timeList,moneyList);
            calendar.removeAllBgColor();
            calendar.setCalendarDaysBgColor(timeList, R.drawable.calendar_day_bg2);
        }
        String f1 = qiandao.getTotalSignTimes()+"";
        String f2 = TextViewUtil.getSumLength(qiandao.getTotalAmount());
        SpannableString tSS = new SpannableString("累计签到 "+ f1 +" 天，累计签到收益 "+ f2+" 元");
        tSS.setSpan(new ForegroundColorSpan(0xFFFFFFFF),5, 5 + f1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tSS.setSpan(new ForegroundColorSpan(0xFFFFFFFF),15 + f1.length(),
                15 + f1.length()+ f2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_top_title.setText(tSS);
    }
    /**
     * 网络请求
     */
    private void loginRequest(String time) {
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1415");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("yearMonth",time);
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, null);
            requen.add(request);
        }
    }

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("签到 ==========" + jobj);
            qiandao = JSON.parseObject(jobj.toString(), QianDaoBean.class);
            if (qiandao.getCode() == -1){
                upData();
            }else {
                ToastManager.showShort(QianDaoAct.this,"请检查网络连接");
            }
        }
    };
    public void showPopwindow(){
        final Dialog dialog = new Dialog(this, R.style.dialog_tran);
        dialog.setContentView(R.layout.popwindow_qiandao);
//        dialog.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画
        TextView tv_income = (TextView) dialog.findViewById(R.id.tv_income);
        tv_income.setText(TextViewUtil.getSumLength(income));
        dialog.show();
        dialog.setCanceledOnTouchOutside(true);

    }
}